package com.business.lgh.naocs.naming.controllers;

import com.business.lgh.nacos.api.naming.common.CommonParams;
import com.business.lgh.nacos.api.naming.common.ConstantValue;
import com.business.lgh.nacos.api.naming.utils.JacksonUtils;
import com.business.lgh.nacos.core.auth.annotation.ActionTypes;
import com.business.lgh.nacos.core.auth.annotation.Secured;
import com.business.lgh.nacos.core.utils.WebUtils;
import com.business.lgh.naocs.naming.constant.UrlPathConstant;
import com.business.lgh.naocs.naming.core.ServiceManager;
import com.business.lgh.naocs.naming.core.pojo.InstanceWrapper;
import com.business.lgh.naocs.naming.core.pojo.InstanceWrapperFacotry;
import com.business.lgh.naocs.naming.web.CanDistro;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @author lgh
 * @version V1.0
 * @Package 实例
 * @date 2020/6/22 7:01 下午
 */
@RestController
@RequestMapping(UrlPathConstant.NACOS_NAMING_CONTEXT+"/instance")
public class InstanceController {

    @Autowired
    ServiceManager serviceManager;

    /**
     * 服务注册接口
     * @param request
     * @return
     * @throws Exception
     */
    @CanDistro
    @PostMapping
    public String register(HttpServletRequest request) throws Exception {
        //必要参数
        final String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
        final String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID,
                ConstantValue.DEFAULT_NAMESPACE_ID);
        //包装成实例（每次都是新包装）
        final InstanceWrapper instance = parseInstance(request);

        //利用service管理类注册实例
        serviceManager.registerInstance(namespaceId, serviceName, instance);
        return "ok";
    }

    @PutMapping("/beat")
    public ObjectNode beat(HttpServletRequest request) throws Exception {
        ObjectNode result = JacksonUtils.createEmptyJsonNode();

        result.put("clientBeatInterval", TimeUnit.SECONDS.toMillis(5));

        //必要参数
        final String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
        final String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID,
                ConstantValue.DEFAULT_NAMESPACE_ID);
//        //包装成实例（每次都是新包装）
        InstanceWrapper instance = parseInstance(request);

        //根据命名空间  服务名  集群名  ip和端口获取示例
        instance = serviceManager.getInstance(namespaceId, instance.getServiceName(),
                instance.getClusterName(), instance.getIp(), instance.getPort());

        if (instance==null){
            instance = parseInstance(request);
            serviceManager.registerInstance(namespaceId, serviceName, instance);
        }
        //更新心跳时间
        serviceManager.restBeatInstance(namespaceId, instance.getServiceName(),
                instance.getClusterName(), instance.getIp(), instance.getPort());

        result.put("code", 10200);
        result.put("lightBeatEnabled", true);
        return result;
    }


    @DeleteMapping
    public String deregister(HttpServletRequest request) throws Exception {
        final String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
        final String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID,
                ConstantValue.DEFAULT_NAMESPACE_ID);
        if (serviceManager.getService(namespaceId,serviceName)==null){
            return "ok";
        }
//        //包装成实例（每次都是新包装）
        InstanceWrapper instance = parseInstance(request);
        serviceManager.deRegisterInstance(namespaceId,serviceName,instance);
        return "ok";
    }

    //通过解析包装成InstanceWrapper
    private InstanceWrapper parseInstance(HttpServletRequest request) {
        InstanceWrapper instance = InstanceWrapperFacotry.getInstance(request);
        instance.validate();
        return instance;
    }


}
